/**
 * Created by sxing on 14-2-6.
 */
(function($) {
    "use strict";

    $.extend($.fn, {
        jqForm: {

        },
        jqFormToken: function(options) {
            var options = $.extend({}, $.fn.jqForm.defaults, options);
            return this.each(function() {
                var $this = $(this);
                var results;
                $.ajax({
                    url: options.tokenUrl,
                    async: false,
                    success:function(data) {
                        results = data;
                    }
                });
                var tokenEl = $this.find("input[name='SYNCHRONIZER_TOKEN']");
                var tokenUriEl = $this.find("input[name='SYNCHRONIZER_URI']");
                if (tokenEl.length ==0) {
                    tokenEl = $('<input>').attr({
                        type: 'hidden',
                        name: 'SYNCHRONIZER_TOKEN'
                    }).appendTo($this);
                }
                if (tokenUriEl.length == 0) {
                    tokenUriEl = $('<input>').attr({
                        type: 'hidden',
                        name: 'SYNCHRONIZER_URI'
                    }).appendTo($this);
                }
                tokenEl.val(results.resetToken);
                tokenUriEl.val(results.resetTokenUri);
            });
        },
        jqSetupForm: function(options) {
            var options = $.extend({}, $.fn.jqForm.defaults, options);
            return this.each(function() {
                var form = $(this);
                var formData;
                if (options.data) {
                    formData = options.data;
                } else if (options.url) {
                    $.ajax({
                        url: options.url,
                        async: true,
                        success:function(data) {
                            formData = data;
                        }
                    });
                }
                formData = typeof formData == "string"?$.parseJSON(formData):formData;
                var $this = $(this);
                $this.data("formData", formData);
                $this.find("input").each(function() {
                    var el = $(this);
                    var nm = el.attr('name');
                    if (!nm) return;
                    if (formData[nm]) {
                        el.val(formData[nm]);
                    }
                });
                for (var prop in formData) {
                    // important check that this is objects own property
                    // not from prototype prop inherited
                    if(formData.hasOwnProperty(prop)){
                       // form.find("input[name="+prop+"]")
                    }
                }
            });
        },
        jqFormClearErr: function(options) {
            var options = $.extend({}, $.fn.jqForm.defaults, options);
            return this.each(function() {
                var $this = $(this);
                var fields = $this.find(options.fieldEl);
                fields.removeClass(options.fieldErrorClass);
                $this.find(options.fieldMsgEl).html('');
                var messageEl = $this.find(options.messageEl);
                messageEl.removeClass(options.errorClass);
                messageEl.addClass(options.messageClass);
                messageEl.html('');
                messageEl.hide();
            });
        },
        jqFormResponse: function(options) {
            var options = $.extend({}, $.fn.jqForm.defaults, options);
            function parseFieldName(name) {
                var pattern = /(\w+)\[(\d+)\]\.(\w+)/;
                var matched = pattern.exec(name);
                if (matched ) {
                    return {field: matched[1], row: parseInt(matched[2]), rowField: matched[3]}
                }
                return name;
            }
            function handleValidateErr(form, fieldErrors) {
                var len = fieldErrors.length;
                var arrayErrors = {};
                for(var i=0;i< len; i++ ) {
                    var error = fieldErrors[i];
                    var msg = error['message'];
                    var fieldName = error['field'];
                    var parsedName = parseFieldName(fieldName);
                    if (typeof parsedName == 'string') {
                        var rejectedValue = error['reject-value'];
                        var fieldEl = form.find(options.fieldElPrefix + fieldName);
                        var errorMsgEl = fieldEl.find(options.fieldMsgEl);
                        fieldEl.addClass(options.fieldErrorClass);
                        errorMsgEl.html(msg);
                    } else {
                        var fieldErrs = arrayErrors[parsedName.field];
                        if (!fieldErrs) {arrayErrors[parsedName.field] = {}; fieldErrs = arrayErrors[parsedName.field]}
                        fieldErrs[msg] = msg;
                        var fieldEl = form.find(options.fieldElPrefix + parsedName.field);
                        var tableId = fieldEl.find('table[id]').attr('id');
                        $(tableId).jqGrid('setCell', parsedName.row, parsedName.field, '', {'background-color':'red'})
                    }
                }
                $.each(arrayErrors, function(field, fieldErrs) {
                    var fieldEl = form.find(options.fieldElPrefix + field);
                    var errorMsgEl = fieldEl.find(options.fieldMsgEl);
                    fieldEl.addClass(options.fieldErrorClass);
                    var ul = errorMsgEl.find('ul');
                    if (ul.length == 0) {
                        errorMsgEl.append('<ul></ul>');
                        ul = errorMsgEl.find('ul');
                    }
                    $.each(fieldErrs, function(msg, value) {
                        ul.append("<li>" + msg + "</li>")
                    });
                });
            }

            return this.each(function() {
                var $this = $(this);
                var results = (typeof options.response == 'string')?$.parseJSON(options.response):options.response;
                var code = Number(results.code);
                var message = results.message;
                var messageEl = $this.find(options.messageEl);

                if (results.resetToken && results.resetTokenUri) {
                    var tokenEl = $this.find("input[name='SYNCHRONIZER_TOKEN']");
                    var tokenUriEl = $this.find("input[name='SYNCHRONIZER_URI']");
                    tokenEl.val(results.resetToken);
                    tokenUriEl.val(results.resetTokenUri);
                }
                if (message) {
                    if (code < 0) {
                        messageEl.removeClass(options.messageClass);
                        messageEl.addClass(options.errorClass);
                    } else {
                        messageEl.removeClass(options.errorClass);
                        messageEl.addClass(options.messageClass);
                    }
                    messageEl.html(message);
                    messageEl.show();
                }
                if (code < 0) {
                    switch(code) {
                        case -407:
                            var errors = results.detail.errors;
                            console.log(errors);
                            if (errors) {
                                handleValidateErr($this, errors);
                            }
                            break;
                        case -401:
                            var loginFormHtml = [
                                "<form class='loginForm'>",
                                "<table>",
                                "   <tr>",
                                "       <td cols='2'>",
                                "           <div class='msg'>请输入用户名和密码</div>",
                                "       </td>",
                                "   </tr>",
                                "   <tr>",
                                "       <td>用户名：</td>",
                                "       <td>",
                                "          <span class='username'></span>",
                                "       </td>",
                                "   </tr>",
                                "   <tr>",
                                "       <td>密 码：</td>",
                                "       <td>",
                                "           <input type='password' name='password' />",
                                "       </td>",
                                "   </tr>",
                                "</table>",
                                "</form>"
                            ];
                            var dialog = bootboxExt.dialog({
                                width: 300, height: 300,
                                message: loginFormHtml.join("\n"),
                                buttons: {
                                    success: {
                                        label: "登录",
                                        className: "btn-success",
                                        callback: function() {
                                            var loginForm = $(".loginForm", dialog);
                                            $(".msg", dialog).html("正在登录...");
                                            var data = {};
                                            $("input", loginForm).each(function(idx, el) {
                                                if (el.name) {
                                                    data[el.name] = $(el).val();
                                                }
                                            });
                                            data['username'] = currentUserName;
                                            $.post(loginUrl, data, function (data, success, req) {
                                                if (success === "success") {
                                                    $(".msg", dialog).html(data.message);
                                                    if (data.code == 0) {
                                                        if (data.resetToken && data.resetTokenUri) {
                                                            var tokenEl = $this.find("input[name='SYNCHRONIZER_TOKEN']");
                                                            var tokenUriEl = $this.find("input[name='SYNCHRONIZER_URI']");
                                                            tokenEl.val(data.resetToken);
                                                            tokenUriEl.val(data.resetTokenUri);
                                                        }
                                                        dialog.modal("hide");
                                                    }
                                                }
                                            });
                                            return false;
                                        }
                                    },
                                    cancel: {
                                        label: "取消",
                                        className: "btn",
                                        callback: function() {
                                            return true;
                                        }
                                    }
                                }
                            });
                            $(".username", dialog).html(currentRealName);
                            break;
                        default:
                    }
                } else {
                    if (options.successUri) {
                        setTimeout(function() {
                            window.location = options.successUri;
                        }, options.directDelay);
                    }
                }
            });

        }
    });
    $.fn.jqForm.defaults = {
        fieldElPrefix : ".field-",
        fieldEl: "form-field",
        fieldMsgEl : ".fieldMsg",
        fieldErrorClass: 'has-error',
        messageEl: '.message',
        messageClass: 'alert-info',
        errorClass: 'alert-danger',
        directDelay: 1000
    };
}(window.jQuery));